package org.aileen.springbook.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.aileen.springbook.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 1.统一结果返回
 * 封装后端接口返回的结果
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    //注入json对象
    @Autowired
    private ObjectMapper objectMapper;

    //在每个接口返回结果之前,都将结果封装成Result对象
    @Override//第一个方法返回的结果表示:是否要对接口返回的结果进行封装
    public boolean supports(MethodParameter returnType, Class converterType) {
        //返回true表示需要对返回结果进行处理
        return true;
    }

    @SneakyThrows
    @Override//在接口,结果返回之前,要做什么事情   ↓body是接口返回的结果
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //①如果body是String类型,需要对其进行特殊处理->需要将它转换成json,然后封装成Result对象
        if(body instanceof String) {
            return objectMapper.writeValueAsString(Result.success(body));
        }

        //②如果对象已经封装成Result对象,就不需要再进行封装了
        if(body instanceof Result<?>) {
            return body;
        }

        //③如果body不是String类型,也不是Result对象,则将其封装成Result对象
        return Result.success(body);
    }
}
